package com.yrot.admin.controller;


import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yrot.admin.entity.SysQuestionBank;
import com.yrot.admin.entity.SysQuestions;
import com.yrot.admin.excel.QuestionIndexModel;
import com.yrot.admin.form.QuestionsAddValid;
import com.yrot.admin.service.ISysQuestionBankService;
import com.yrot.admin.service.ISysQuestionsService;
import com.yrot.common.annotation.SysLog;
import com.yrot.common.result.R;
import com.yrot.common.result.Result;
import com.yrot.common.result.ResultUtils;
import com.yrot.common.utils.EasyExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hemin
 * @since 2019-04-02
 */
@RestController
@RequestMapping("/admin/question/")
public class SysQuestionsController extends BaseController{

    @Autowired
    ISysQuestionsService questionsService;

    @Autowired
    ISysQuestionBankService questionBankService;


    @GetMapping("questions")
    public Result questionBanks(int page, int limit,
                                @RequestParam(required = false) String questionContent,
                                @RequestParam(required = false) Integer questionType,
                                @RequestParam(required = false) Integer bankId){
        QueryWrapper<SysQuestions> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(questionContent)){
            queryWrapper.like("question_content",questionContent);
        }
        if(questionType != null){
            queryWrapper.eq("question_type",questionType);
        }
        if(bankId != null){
            queryWrapper.eq("bank_id",bankId);
        }
        //过滤条件 查询本人的所有题目
        QueryWrapper<SysQuestionBank> bankQueryWrapper = new QueryWrapper<>();
        bankQueryWrapper.eq("expert_id",sysExpert().getExpertId());
        List<SysQuestionBank> myBanks = questionBankService.list(bankQueryWrapper);
        List myBankIds = new ArrayList<Integer>();
        for (SysQuestionBank myBank : myBanks) {
            myBankIds.add(myBank.getBankId());
        }
        if(myBankIds.isEmpty()){
            return ResultUtils.success(new Long(0),null);
        }
        //myBankIds = myBankIds.substring(1);
        queryWrapper.in("bank_id",myBankIds);
        queryWrapper.orderByDesc("question_id");
        Page<SysQuestions> pages = new Page<>(page, limit);
        //List<SysQuestionBank> list = questionBankService.list(null);
        IPage<SysQuestions> questionsIPage = questionsService.page(pages, queryWrapper);
        List<SysQuestions> records = questionsIPage.getRecords();
        List<QuestionsAddValid> recordsFormat = new ArrayList<>();
        myBanks.forEach(bank -> {
            records.forEach(question -> {
                if(bank.getBankId() == question.getBankId()){
                    QuestionsAddValid questionsAddValid = new QuestionsAddValid();
                    BeanUtils.copyProperties(question,questionsAddValid);
                    questionsAddValid.setBankName(bank.getBankName());
                    recordsFormat.add(questionsAddValid);
                }
            });
        });

        return ResultUtils.success(questionsIPage.getTotal(),recordsFormat);
    }

    @PostMapping("question")
    public R questionBanks(@Valid QuestionsAddValid questionsAddValid, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return R.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        SysQuestions sysQuestions = new SysQuestions();
        BeanUtils.copyProperties(questionsAddValid,sysQuestions);
        boolean save = questionsService.save(sysQuestions);
        if(save){
            return R.ok();
        }
        return R.error("添加题目失败");
    }

    @PutMapping("question")
    @SysLog("编辑题目")
    public R updateQuestion(@Valid QuestionsAddValid questionsAddValid, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return R.error(bindingResult.getFieldError().getDefaultMessage());
        }
        SysQuestions sysQuestions = new SysQuestions();
        BeanUtils.copyProperties(questionsAddValid,sysQuestions);
        boolean status = questionsService.saveOrUpdate(sysQuestions);
        if(status){
            return R.ok();
        }
        return R.error("添加修改失败");
    }

    @DeleteMapping("question/{questionId}")
    public void deleteQuestion(@PathVariable("questionId")Integer questionId){
        questionsService.removeById(questionId);
    }

    @DeleteMapping("questions")
    @SysLog("批量删除题目")
    public void deleteQuestions(@RequestParam String questionIds){
        questionsService.removeByIds(Arrays.asList(questionIds.split(",")));
    }

    @PostMapping("upload")
    @SysLog("导入题目")
    public R upload(@RequestParam("file") MultipartFile file){
        String contentType = file.getContentType();
        if(file.isEmpty()){
            return R.error("文件不能为空");
        }
        if(!contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
            return R.error("文件类型错误，请上传xls格式");
        }
        return questionsService.upload(file);
    }

    @GetMapping("export")
    @SysLog("导出题目")
    public void export(@RequestParam(required = false) Integer questionType,
                       @RequestParam(required = false) Integer bankId,
                       HttpServletResponse response){
        EasyExcelUtil.writeExcelWebWithModel(response,getData(questionType,bankId),QuestionIndexModel.class,ExcelTypeEnum.XLSX,"题目信息.xlsx");
    }

    private List<QuestionIndexModel> getData(Integer questionType,Integer bankId){
        ArrayList<QuestionIndexModel> models = new ArrayList<>();
        QueryWrapper<SysQuestions> queryWrapper = new QueryWrapper<>();
        if(questionType != null){
            queryWrapper.eq("question_type",questionType);
        }
        if(bankId != null){
            queryWrapper.eq("bank_id",bankId);
        }
        QueryWrapper<SysQuestionBank> bankQueryWrapper = new QueryWrapper<>();
        bankQueryWrapper.eq("expert_id",sysExpert().getExpertId());
        List<SysQuestionBank> myBanks = questionBankService.list(bankQueryWrapper);
        String myBankIds = "";
        for (SysQuestionBank myBank : myBanks) {
            myBankIds += "," + myBank.getBankId();
        }
        if(StringUtils.isEmpty(myBankIds)){
            return null;
        }
        myBankIds = myBankIds.substring(1);
        queryWrapper.in("bank_id",myBankIds);
        queryWrapper.orderByDesc("question_id");
        List<SysQuestions> records = questionsService.list(queryWrapper);
        for (SysQuestions record : records) {
            QuestionIndexModel model = new QuestionIndexModel();
            BeanUtils.copyProperties(record,model);
            switch (model.getQuestionType()){
                case 0:model.setType("判断题");break;
                case 1:model.setType("单选题");break;
                case 2:model.setType("多选题");break;
            }
            models.add(model);
        }
        myBanks.forEach(bank -> {
            models.forEach(model -> {
                if(bank.getBankId() == model.getBankId()){
                    model.setBankName(bank.getBankName());
                }
            });
        });
        return models;
    }


}
